package ru.uskov.trainer;

import java.io.CharArrayWriter;
import java.io.Reader;
import java.util.Map;
import java.util.Properties;

import javax.servlet.http.Cookie;

//import org.apache.log4j.Logger;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import ru.uskov.trainer.model.UserAuthData;


public class Utils {
  //private static Logger logger = Logger.getLogger(Utils.class);
  
  public static UserAuthData getUserId(Cookie[] cookies) {
    if (cookies != null) {
      Long id = 0l;
      String pwd = "";
      for (Cookie c : cookies) {
        if (MainPage.USER_ID_COOKIE_NAME.equals(c.getName())) {
          //logger.info("Connected User with id = " + c.getValue());
          try {
            id = Long.parseLong(c.getValue());
          } catch (NumberFormatException e) {
            System.out.println("smth wrong");//TODO
          }
        }
        if (MainPage.USER_ID_COOKIE_PWD.equals(c.getName())) {
          pwd = c.getValue();
        }
      }
      return new UserAuthData(id, pwd);
    }
    return null;
  }
  
  public static String compileTemplate(Reader reader, Map<String, Object> arguments) {
    try {
      Properties p = new Properties();
      p.setProperty("runtime.log.logsystem.class", "org.apache.velocity.runtime.log.NullLogSystem");
      p.setProperty("resource.loader","class");
      p.setProperty("class.resource.loader.description", "Classpath Loader");
      p.setProperty("input.encoding", "CP1251");
      p.setProperty("output.encoding", "UTF-8");
      p.setProperty("class.resource.loader.class",
             "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");


      Velocity.init(p);
      VelocityContext context = new VelocityContext();
      for (Map.Entry<String, Object> entry : arguments.entrySet()) {
        context.put(entry.getKey(), entry.getValue());
      }
      //ByteArrayOutputStream os =new ByteArrayOutputStream(); 
      CharArrayWriter out = new CharArrayWriter();//new OutputStreamWriter(os, "UTF-8");      
      Velocity.evaluate(context, out, "", reader);
      //logger.debug("Compiled template to " + new String(out.toCharArray()));
      return new String(out.toCharArray());//new String(os.toByteArray(), Second.CODEPAGE);
    } catch (Exception exception) {
      return exception.toString();
    }
  }
}

